package cn.edu.seu.herald.informationplatform.filter;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.seu.herald.informationplatform.bean.auth.CommonUserAuthorization;
import cn.edu.seu.herald.informationplatform.bean.auth.LeagueSession;
import cn.edu.seu.herald.informationplatform.bean.auth.LeagueUserAuthorization;
import cn.edu.seu.herald.informationplatform.bean.auth.UserSession;
import cn.edu.seu.herald.informationplatform.dao.cookie.CommonUserSessionCookieAccess;
import cn.edu.seu.herald.informationplatform.dao.cookie.LeagueUserSessionCookieAccess;
import cn.edu.seu.herald.informationplatform.dao.cookie.SessionIdNotFound;
import cn.edu.seu.herald.informationplatform.dao.database.LeagueInfoDao;
import cn.edu.seu.herald.informationplatform.dao.database.LeagueSessionDao;
import cn.edu.seu.herald.informationplatform.dao.database.LeagueUserDao;
import cn.edu.seu.herald.informationplatform.dao.database.UserDao;
import cn.edu.seu.herald.informationplatform.dao.database.UserSessionDao;

public class UserAuthorized  implements Filter {
	
	public static final String COMMON_USER_AUTH_BEAN = "commonUserAuth";
	
	public static final String LEAGUE_USER_AUTH_BEAN = "leagueUserAuth";

	public static String COMMON_USER_SESSION_ID_COOKIE_NAME =
			"COMMON_USER_SESSION_ID";

	public static String LEAGUE_USER_SESSION_ID_COOKIE_NAME =
			"LEAGUE_USER_SESSION_ID";

	@Override
	public void init(FilterConfig config) throws ServletException {
	}

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request,
			ServletResponse response, FilterChain chain)
					throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;

		/*try {
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
			CommonUserSessionCookieAccess cUserSessionAccess =
					new CommonUserSessionCookieAccess(httpRequest);
			if (cUserSessionAccess.isAuthorized()) {
				CommonUserAuthorization auth = new CommonUserAuthorization();
				auth.setUserId(cUserSessionAccess.getUserId());
				auth.setUsername(cUserSessionAccess.getUsername());
				httpRequest.setAttribute(COMMON_USER_AUTH_BEAN,
						auth);
			}
		} catch (Exception e) {}
			
		try {
			LeagueUserSessionCookieAccess lUserSessionAccess =
					new LeagueUserSessionCookieAccess(httpRequest);
			String leagueParam =
					httpRequest.getParameter(LeagueSpecified.PARAM_NAME_OF_LEAGUE_ID);
			int leagueId = Integer.valueOf(leagueParam);
			if (lUserSessionAccess.getLeagueId() == leagueId
					&& lUserSessionAccess.isAuthorized()) {
				LeagueUserAuthorization auth = new LeagueUserAuthorization();
				auth.setLeagueId(lUserSessionAccess.getLeagueId());
				auth.setUsername(lUserSessionAccess.getUsername());
				httpRequest.setAttribute(LEAGUE_USER_AUTH_BEAN,
						auth);
			}
		} catch (Exception e) {
			StringBuilder b = new StringBuilder();
			for (Cookie c: httpRequest.getCookies()) {
				String name = c.getName();
				String value = c.getValue();
				String domain = c.getDomain();
				b.append("[" + "name:" + name + ", value:" + value + ", domain:" + domain + "]");
			}
			httpResponse.sendError(402, b.toString());
			httpResponse.sendError(402, (String) request.getAttribute("test"));
			return;
		}*/
		try {
			build(httpRequest, httpResponse);
		} catch (Exception e) {
			httpResponse.sendError(500, e.getMessage());
		}
		chain.doFilter(request, response);
	}
	
	private void build(HttpServletRequest httpRequest,
			HttpServletResponse httpResponse) throws NumberFormatException, SQLException, IOException {
		Cookie[] cookies = httpRequest.getCookies();
		boolean userFlag = true;
		boolean leagueFlag = true;
		if (cookies != null) {
			for (Cookie cookie: cookies) {
				String name = cookie.getName();
				if (userFlag &&
						name.equalsIgnoreCase(COMMON_USER_SESSION_ID_COOKIE_NAME)) {
					String value = cookie.getValue();
					UserSessionDao dao = UserSessionDao.getDao();
					UserDao uDao = UserDao.getDao();
					if (dao.contains(Integer.valueOf(value))) {
						UserSession session =
								dao.getUserSessionById(Integer.valueOf(value));
						int userId = session.getUserId();
						String username = uDao.getUserById(userId).getTruename();
						CommonUserAuthorization auth = new CommonUserAuthorization();
						auth.setUserId(session.getUserId());
						auth.setUsername(username);
						httpRequest.setAttribute(COMMON_USER_AUTH_BEAN, auth);
					}
					userFlag = false;
				}
				if (leagueFlag &&
						name.equalsIgnoreCase(LEAGUE_USER_SESSION_ID_COOKIE_NAME)) {
					String value = cookie.getValue();
					LeagueSessionDao dao = LeagueSessionDao.getDao();
					LeagueUserDao luDao = LeagueUserDao.getDao();
					LeagueInfoDao liDao = LeagueInfoDao.getDao();
					if (dao.contains(Integer.valueOf(value))) {
						LeagueSession session =
								dao.getLeagueSessionById(Integer.valueOf(value));
						int leagueId = session.getLeagueId();
						String username =
								liDao.getLeagueInfo(luDao.getLeagueUser(leagueId)
										.getLeagueInfoId()).getName();
						LeagueUserAuthorization auth = new LeagueUserAuthorization();
						auth.setLeagueId(leagueId);
						auth.setUsername(username);
						httpRequest.setAttribute(LEAGUE_USER_AUTH_BEAN, auth);
					}
					leagueFlag = false;
				}
			}
		}
	}

}
